package fr.sedoo.metadata.client.ui.widget.field.impl.keyword;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Widget;

import fr.sedoo.commons.client.callback.LoadCallBack;
import fr.sedoo.commons.client.widget.dialog.OkCancelContent;
import fr.sedoo.commons.client.widget.editing.EditionCallBack;
import fr.sedoo.metadata.shared.domain.thesaurus.SingleLevelThesaurus;
import fr.sedoo.metadata.shared.domain.thesaurus.ThesaurusItem;

public class SingleLevelThesaurusDialogContent extends Composite implements OkCancelContent, LoadCallBack {

	@UiField
	SingleLevelThesaurusSelectionTable selectionTable;

	private static SingleLevelThesaurusDialogContentUiBinder uiBinder = GWT.create(SingleLevelThesaurusDialogContentUiBinder.class);

	private EditionCallBack<ArrayList<ThesaurusItem>> callback;

	private List<ThesaurusItem> selectedItems;

	interface SingleLevelThesaurusDialogContentUiBinder extends UiBinder<Widget, SingleLevelThesaurusDialogContent> {
	}

	public SingleLevelThesaurusDialogContent(String language, SingleLevelThesaurus thesaurus, List<ThesaurusItem> selectedItems, EditionCallBack<ArrayList<ThesaurusItem>> callback) {
		super();
		this.selectedItems = selectedItems;
		this.callback = callback;
		initWidget(uiBinder.createAndBindUi(this));
		reset();
		ClientThesaurusList.getThesaurusItems(thesaurus.getId(), language, this);
	}

	private void reset() {
		selectionTable.reset();
	}

	private DialogBox dialog;

	@Override
	public void setDialogBox(DialogBox dialog) {
		this.dialog = dialog;
	}

	public DialogBox getDialog() {
		return dialog;
	}

	@Override
	public void okClicked() {
		if (getDialog() != null) {
			getDialog().hide();
			callback.postEditProcess(true, selectionTable.getSelectedItems());
		}
	}

	@Override
	public void cancelClicked() {
		if (getDialog() != null) {
			selectionTable.reset();
			getDialog().hide();
		}

	}

	@Override
	public String getPreferredHeight() {
		return "200px";
	}

	@Override
	public void postLoadProcess(Object result) {
		ArrayList<ThesaurusItem> aux = (ArrayList<ThesaurusItem>) result;
		reset();
		selectionTable.setThesaurusItems(aux, selectedItems);

		// items.clear();
		// for (ThesaurusItem thesaurusItem : aux) {
		// items.addItem("www" + thesaurusItem.getValue(),
		// thesaurusItem.getId());
		// }
		//
		// int itemCount = items.getItemCount();
		// for (int i = 0; i < itemCount; i++) {
		// items.setItemSelected(i, false);
		// System.out.println(items.getValue(i) + " -" + items.getItemText(i));
		// }
		//
		// items.update();
	}

}
